package com.boarsoft.boar.config.apollo.listener;

import com.boarsoft.config.manager.PropConfigManager;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Field;
/**
 * 基于apollo-client封装的配置类变更监听器
 *
 */
public class ApolloConfigChangeListener implements ConfigChangeListener {
    @Override
    public void onChange(ConfigChangeEvent configChangeEvent) {
        for(String k:configChangeEvent.changedKeys()) {
            Object obj = PropConfigManager.getResource(configChangeEvent.getChange(k).getNamespace());
            try {
                Field f=obj.getClass().getDeclaredField(k);
                f.setAccessible(true);
                f.set(obj, ConvertUtils.convert(configChangeEvent.getChange(k).getNewValue(),f.getType()));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
